package com.eco.fanliapp.job.integralOrder;

import com.eco.fanliapp.common.OrderTaskUtils;
import com.eco.fanliapp.entity.TaobaoScheme;
import com.eco.fanliapp.service.IJobIntegralOrderInfoHandleService;
import com.eco.fanliapp.service.IJobOrderInfoHandleNewService;
import com.eco.fanliapp.utils.DateCalculateUtils;
import com.eco.fanliapp.utils.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 拉取2个月内积分订单
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class integralOrderTask implements Job, Serializable {

    private static final Logger log = LoggerFactory.getLogger(integralOrderTask.class);
    private String timeFlagIntegralOrder ="";

    @Autowired
    private IJobIntegralOrderInfoHandleService iJobIntegralOrderInfoHandleService;

    @Autowired
    private OrderTaskUtils orderTaskUtils;
    @Autowired
    private RedisTemplate redisTemplate;

    public integralOrderTask(){

    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        //取得job详情
        JobDetail jobDetail = context.getJobDetail();
        JobDataMap dataMap =  jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }
        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long beginTime = System.currentTimeMillis();
        log.info("***************************************开始执行定时任务-拉取 积分兑换订单 定时任务-OrderTwoMonthTaskNewMMMM：executeCount="+executeCount+"--beginTime="+beginTime);

        //获取淘宝联盟账号-排除已过期的
        List<TaobaoScheme> taobaoSchemes = orderTaskUtils.getUsedTaobaoScheme();
        //判断联盟
        //开始时间、结束时间
//        String startTime = orderTaskUtils.getSystemTime();//.replace(" ", "%20");
//        String endTime = orderTaskUtils.getNowTime();
//        iJobIntegralOrderInfoHandleService.handlePayOrder(startTime, endTime, taobaoSchemes, 1);
//        iJobIntegralOrderInfoHandleService.handleSettleOrder(startTime, endTime, taobaoSchemes, 1);
//        iJobIntegralOrderInfoHandleService.handleFailOrder(startTime, endTime, taobaoSchemes, 1);
//        iJobIntegralOrderInfoHandleService.handleSettleOrder(startTime, endTime, taobaoSchemes, 1);


        //切分时间
        List<String> list = handleTime(timeFlagIntegralOrder);
        String startTime = null;
        String endTime = null;
        if(CollectionUtils.isNotEmpty(list)){
            for(String time:list){
                if (startTime == null) {
                    startTime = time;
                    continue;
                }
                endTime = time;
                Long dealEndTime = DateUtils.datestr2LongByFormt(endTime, null);
                if (dealEndTime >= (System.currentTimeMillis() - 1000L * 60 * 20)) {
                    continue;
                }
                log.info("开始拉取1月积分兑换订单-开始时间{}、结束时间{}", startTime, endTime);
                //处理订单
                iJobIntegralOrderInfoHandleService.handlePayOrder(startTime, endTime, taobaoSchemes, 1);
                iJobIntegralOrderInfoHandleService.handleCompleteOrder(startTime, endTime, taobaoSchemes, 1);
                iJobIntegralOrderInfoHandleService.handleFailOrder(startTime, endTime, taobaoSchemes, 1);
                iJobIntegralOrderInfoHandleService.handleSettleOrder(startTime, endTime, taobaoSchemes, 1);
                log.info("结束拉取 积分兑换订单 -开始时间{}、结束时间{}", startTime, endTime);
                startTime = time;
            }
        }
        log.info("***************************************结束执行定时任务-拉取 积分兑换订单 定时任务-OrderTwoMonthTaskNew：executeCount=" + executeCount + "--endTime=" + System.currentTimeMillis() + "--耗时=" + (System.currentTimeMillis() - beginTime));

    }

    /**
     * 处理时间
     * @param timeFlag
     * @return
     */
    public static List<String> handleTime(String timeFlag){
        //当前日期参照点
        Date currentTime = new Date();
        String currentTimeStr = DateUtils.date2Str(currentTime, null);
        if (timeFlag == null || "".equals(timeFlag)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentTime);
            calendar.add(Calendar.MINUTE, -(2 * 60 + 20));
//            calendar.add(Calendar.MINUTE, -(60));
            timeFlag = DateUtils.date2Str(calendar.getTime(), null);
            log.info("拉取 订单定时任务-开始2个月时间参照点{}", timeFlag);
        }
        //切割时间段(交易类型 M/D/H/N -->每月/每天/每小时/每分钟,多久分成一份，开始时间，结束时间)
        List<String> list = DateCalculateUtils.cutDate("N",1200, timeFlag, currentTimeStr);
        return list;
    }

    public static void main(String[] args) {
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(new Date());
////        calendar.add(Calendar.MINUTE, -(24*60+20));
//        String str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(calendar.getTime());
//        System.out.println(str);
        List<String> strings = handleTime("");
        System.out.println(strings);
    }


}
